library(lmtest)
library(plm)
library(RCurl)
library(lme4)
library(tidyverse)
library(lazyeval)
library(reshape2)
library(readstata13)
library(rdrobust)
library(foreign)
library(magrittr)
library(openxlsx)
library(stargazer)

select <- dplyr::select


#############################Plotting STATA Diff in Diff Output#############################
# set your directory here
setwd("")

files <- list.files(path = './Data/', pattern = ".csv")

marginslist <- list()
for (i in 1:length(files)){
  
  temp <- read.csv(files[i], skip=1)
  
  temp <- temp[grepl("cand", temp$X)==T,]
  
  temp$filename <- files[i]
  
  temp$dvr <- ""
  if(grepl("_A_", files[i])==T){
    temp$dvr <- "Asian"}
  if(grepl("_B_", files[i])==T){
    temp$dvr <- "Black"}
  if(grepl("_H_", files[i])==T){
    temp$dvr <- "Latino"}
  if(grepl("_NW_", files[i])==T){
    temp$dvr <- "Contributors of Color"}
  if(grepl("_W_", files[i])==T){
    temp$dvr <- "White Contributors"}
  
  temp$test <- ""
  if(temp$dvr==""){temp$test <- "Gender Only"}
  else if(grepl("_2g", files[i])==T){
    temp$test <- "White/Non-White"} else{
      temp$test <- "All Ethnoraces"
    }
  
  temp$dvg <- ""
  if(grepl("1.", files[i])==T){
    temp$dvg <- "Female Contributors"}
  if(grepl("0.", files[i])==T){
    temp$dvg <- "Male Contributors"}
  
  #if(grepl("house_", files[i])==T){
  #  temp$seat <- "U.S. House"
  #} else {temp$seat <- "All"}
  
  if(grepl("_candd", files[i])==T){
    temp$cand_party <- "Democrats"
  }
  if(grepl("_candr", files[i])==T){
    temp$cand_party <- "Republicans"
  }
  if(grepl("_candall", files[i])==T){
    temp$cand_party <- "All"
  }
  
  if(grepl("_contribd", files[i])==T){
    temp$contrib_party <- "Democrats"
  }
  if(grepl("_contribr", files[i])==T){
    temp$contrib_party <- "Republicans"
  }
  if(grepl("_contriball", files[i])==T){
    temp$contrib_party <- "All"
  }
  
  if(grepl("_primary_", files[i])==T){
    temp$time <- "Primary Election Money"}
  else if(grepl("_all_", files[i])==T){
      temp$time <- "Total Election Money"
  }else {temp$time <- "General Election Money"}
  
  if(grepl("log", files[i])==T){
    temp$type1 <- "Log "
  } 
  else if(grepl("share", files[i])==T){
    temp$type1 <- "Share "}
  else {temp$type1 <- ""}
  
  temp$type <- paste0(temp$type1, "Total")
  
  if(grepl("distcv", files[i])==T){
    temp$district_covs <- "District"
  }
  else if(grepl("candcv", files[i])==T){
    temp$district_covs <- "Candidate"
  }
  else if(grepl("ideocv", files[i])==T){
    temp$district_covs <- "Ideology"
  }
  else if(grepl("compcv", files[i])==T){
    temp$district_covs <- "Competitiveness"
  } else {temp$district_covs <- "None"}
  
  if(grepl("_nofe", files[i])==T){
    temp$fe <- "No FEs"
  } else {temp$fe <- "FEs"}
  
  temp <- temp %>% mutate_if(is.factor, as.character)
  temp$se <- ifelse(temp$se==".", NA, as.numeric(temp$se))
  
  marginslist[[i]] <- temp
}

plotdata <- do.call(bind_rows, marginslist)

## NEED TO UPDATE THIS CODE WITH NEW COVARIATE TYPES FYI ##

#DID table for Appendix
tabledata <- plotdata[plotdata$district_covs!="All",-c(7, 8, 9,11)]

tabledata$X[grepl("A_", tabledata$X)] <- "Asian"
tabledata$X[grepl("B_", tabledata$X)] <- "Black"
tabledata$X[grepl("H_", tabledata$X)] <- "Latino"

names(tabledata) <- c("Cand. Ethnorace", "Est.", "SE", "Contributor Ethnorace", "Cand. Party", "Recipient Party", "DV", "Controls")
tabledata <- tabledata[,c(1,4,5,6,7,8,2,3)]

tabledata_share <- tabledata[str_detect(tabledata$DV, "Share"),]
tabledata_logtotal <- tabledata[str_detect(tabledata$DV,"Log Total"),]

tabledata_share_clean <- tabledata_share[tabledata_share$DV=="Share Total" & tabledata_share$Controls!="No FEs",]
tabledata_share_clean$DV <- "Share"

#Clean
for (i in levels(factor(tabledata$`Contributor Ethnorace`))){
  
  stargazer(tabledata_share_clean[tabledata_share_clean$`Contributor Ethnorace`==i,], out=paste("clean_did_table_share_", i, ".tex", sep=""), 
            summary=F, style="ajps", rownames=F, digits=3, digits.extra=3)
}


#Full
for (i in levels(factor(tabledata$`Contributor Ethnorace`))){
  
  stargazer(tabledata_share[tabledata_share$`Contributor Ethnorace`==i,], out=paste("did_table_share_", i, ".tex", sep=""), 
            summary=F, style="ajps", rownames=F, digits=3, digits.extra=3)
  stargazer(tabledata_logtotal[tabledata_logtotal$`Contributor Ethnorace`==i,], out=paste("did_table_logtotal_", i, ".tex", sep=""), 
            summary=F, style="ajps", rownames=F, digits=3, digits.extra=3)
  
}


# creats ALL the plots
plotdata$cilow <- plotdata$b - 1.96*plotdata$se
plotdata$cihigh <- plotdata$b + 1.96*plotdata$se

pd <- position_dodge(0.2)


plotdata %<>% 
  filter(!(dvr=="" & dvg=="")) %>%
  mutate(typelc = str_to_lower(str_remove_all(type, " ")))
key <- plotdata %>% group_by(type, typelc) %>% summarise() %>% as.data.frame()

# looking at primary/general/all
for(contrib in c("Democrats", "Republicans")){
  
  labels <- c("cand_1_d" = "Dem. Female\nCandidate",
              "cand_1_r" = "Rep. Female\nCandidate",
              "cand_1_all" = "Female Candidate\n(Either Party)\n")
  
  # getting info for filename
  typelc <- key[key$type==t, 'typelc']
  
  # setting axes
  if(str_detect(t,"Log")){ylims <- c(-1,2)}
  else if(str_detect(t,"Share")){ylims <- c(-.2,.5)} else{ylims <- c(-2e05,2e05)}
  
  temp_data <- plotdata %>% filter(type==t & 
                                     contrib_party==contrib & 
                                     fe=="FEs" &
                                     cand_party!="All" &
                                     district_covs=='Candidate' & 
                                     dvr=="")
  
  if(nrow(temp_data)==0){next}
  
  ggplot(temp_data, 
         aes(x=X, y=b, color=time)) +
    geom_point(position=pd) +
    geom_errorbar(aes(ymin=cilow, ymax=cihigh), width=0, position=pd) +
    facet_wrap(~dvg) +
    xlab("") +
    ylab(paste0(t, " of ", 
                ifelse(contrib=="Democrats", "Dem. ", 
                       ifelse(contrib=="Republicans", "Rep. ", "")), 
                "General Election Individual Contribs.")) +
    geom_hline(aes(yintercept=0), linetype=2, color="black") +
    scale_color_grey(name="Controls") +
    scale_x_discrete(labels=labels) +
    coord_flip(ylim=ylims) +
    theme_classic()
  ggsave(paste0("./Output/time_",
                typelc,
                "contrib",
                ifelse(contrib=="Democrats", "dem", 
                       ifelse(contrib=="Republicans", "rep", "all")), 
                ".pdf"),
         width=7, height=5)
}

# looking at different sets of covariates
for(t in unique(plotdata$type)){
  for(contrib in c("Democrats", "Republicans")){
    
    labels <- c("cand_1_d" = "Dem. Female\nCandidate",
                "cand_1_r" = "Rep. Female\nCandidate",
                "cand_1_all" = "Female Candidate\n(Either Party)\n")
  
    # getting info for filename
    typelc <- key[key$type==t, 'typelc']
    
    # setting axes
    if(str_detect(t,"Log")){ylims <- c(-1,2)}
    else if(str_detect(t,"Share")){ylims <- c(-.2,.5)} else{ylims <- c(-2e05,2e05)}
    
    temp_data <- plotdata %>% filter(type==t & 
                                       contrib_party==contrib & 
                                       fe=="FEs" &
                                       cand_party!="All" &
                                       time=='Total Election Money' & 
                                       dvr=="")
    
    if(nrow(temp_data)==0){next}
    
    ggplot(temp_data, 
           aes(x=X, y=b, color=district_covs)) +
      geom_point(position=pd) +
      geom_errorbar(aes(ymin=cilow, ymax=cihigh), width=0, position=pd) +
      facet_wrap(~dvg) +
      xlab("") +
      ylab(paste0(t, " of ", 
                  ifelse(contrib=="Democrats", "Dem. ", 
                         ifelse(contrib=="Republicans", "Rep. ", "")), 
                  "General Election Individual Contribs.")) +
      geom_hline(aes(yintercept=0), linetype=2, color="black") +
      scale_color_grey(name="Controls") +
      scale_x_discrete(labels=labels) +
      coord_flip(ylim=ylims) +
      theme_classic()
    ggsave(paste0("./Output/covars_",
                  typelc,
                  "contrib",
                  ifelse(contrib=="Democrats", "dem", 
                         ifelse(contrib=="Republicans", "rep", "all")), 
                  ".pdf"),
           width=7, height=5)
  }
}

# NW/W
for(t in unique(plotdata$type)){
  for(contrib in c("Democrats", "Republicans", "All")){
    for(cand in c("Democrats", "Republicans", "All")){
      
      if(cand=="Democrats"){
        labels <- c("cand_int_W_1_d" = "Dem. White\nCandidate", 
                    "cand_int_NW_0_d" = "Dem. Candidate\nof Color",
                    "cand_int_NW_1_d" = "Dem. Candidate\nof Color")
      }
      if(cand=="Republicans"){
        labels <- c("cand_int_W_1_d" = "Rep. White\nCandidate", 
                    "cand_int_NW_0_d" = "Rep. Candidate\nof Color",
                    "cand_int_NW_1_d" = "Rep. Candidate\nof Color")
      }
      if(cand=="All"){
        labels <- c("cand_int_W_1_d" = "White\nCandidate", 
                    "cand_int_NW_0_d" = "Candidate\nof Color",
                    "cand_int_NW_1_d" = "Candidate\nof Color")
      }
      
      # getting info for filename
      typelc <- key[key$type==t, 'typelc']
      
      # setting axes
      if(str_detect(t,"Log")){ylims <- c(-1,2)}
      if(str_detect(t,"Share")){ylims <- c(-.2,.2)}
      
      temp_data <- plotdata %>% 
        filter(type==t &   
                 contrib_party==contrib & 
                 test=="White/Non-White" &
                 district_covs %in% c("Yes") & 
                 cand_party==cand & 
                 test=="White/Non-White") %>%
        mutate(contrib_gender = ifelse(str_detect(X, "1"), "Female", "Male"),
               label = ifelse(str_detect(X, "NW"), "Candidate\nof Color", "White\nCandidate"))
      
      if(nrow(temp_data)==0){next}
      
      ggplot(temp_data, 
             aes(x=label, y=b, color=contrib_gender)) +
        geom_point(position=pd) +
        geom_errorbar(aes(ymin=cilow, ymax=cihigh), width=0, position=pd) +
        facet_grid(dvg~dvr) +
        xlab("") +
        ylab(paste0(t, " of ", 
                    ifelse(contrib=="Democrats", "Dem. ", 
                           ifelse(contrib=="Republicans", "Rep. ", "")), 
                    "General Election Individual Contribs.")) +
        geom_hline(aes(yintercept=0), linetype=2, color="black") +
        scale_color_manual(values=c("black", "grey"), name="Candidate\nGender") +
        scale_x_discrete(labels=labels) +
        coord_flip(ylim=ylims) +
        theme_classic()
      ggsave(paste0("./Output/didNW",
                    typelc,
                    "cand",
                    ifelse(cand=="Democrats", "dem", 
                           ifelse(cand=="Republicans", "rep", "all")), 
                    "_contrib",
                    ifelse(contrib=="Democrats", "dem", 
                           ifelse(contrib=="Republicans", "rep", "all")), 
                    ".pdf"),
             width=7, height=5)
    }
  }
}

## FIGURE 4 IN MANUSCRIPT ##
for(t in unique(plotdata$type)){
  for(contrib in c("Democrats", "Republicans", "All")){
    for(cand in c("Democrats", "Republicans", "All")){
      
      if(cand=="Democrats"){
        labels <- c("cand_H_d" = "Dem. Latino\nCandidate", 
                    "cand_B_d" = "Dem. Black\nCandidate", 
                    "cand_A_d" = "Dem. Asian\nCandidate")
      }
      if(cand=="Republicans"){
        labels <- c("cand_H_r" = "Rep. Latino\nCandidate", 
                    "cand_B_r" = "Rep. Black\nCandidate", 
                    "cand_A_r" = "Rep. Asian\nCandidate")
      }
      if(cand=="All"){
        labels <- c("cand_H_all" = "Latino\nCandidate", 
                    "cand_B_all" = "Black\nCandidate", 
                    "cand_A_all" = "Asian\nCandidate")
      }
      
      # getting info for filename
      typelc <- key[key$type==t, 'typelc']
      
      # setting axes
      if(str_detect(t,"Log")){ylims <- c(-2,4)}
      if(str_detect(t,"Share")){ylims <- c(-.2,.2)}
      
      temp_data <- plotdata %>% filter(type==t & 
                                         contrib_party==contrib & 
                                         fe=="FEs" &
                                         time=='General Election Money' & 
                                         cand_party!="All" &
                                         district_covs=='Candidate' & 
                                         dvr!="" & dvg!="") %>%
        mutate(contrib_gender = ifelse(str_detect(X, "1"), "Female", "Male"),
               label = ifelse(str_detect(X, "B"), "Black\nCandidate",
                              ifelse(str_detect(X, "H"), "Latino\nCandidate",
                                     ifelse(str_detect(X, "A"), "Asian\nCandidate", "White\nCandidate"))))
                                       
        
      
      if(nrow(temp_data)==0){next}
      
      ggplot(temp_data, 
             aes(x=label, y=b, color=contrib_gender)) +
        geom_point(position=pd) +
        geom_errorbar(aes(ymin=cilow, ymax=cihigh), width=0, position=pd) +
        facet_grid(dvg~dvr) +
        xlab("") +
        ylab(paste0(t, " of ", 
                    ifelse(contrib=="Democrats", "Dem. ", 
                           ifelse(contrib=="Republicans", "Rep. ", "")), 
                    "General Election Individual Contribs.")) +
        geom_hline(aes(yintercept=0), linetype=2, color="black") +
        scale_color_manual(values=c("black", "grey"), name="Candidate\nGender") +
        #scale_x_discrete(labels=labels) +
        coord_flip(ylim=ylims) +
        theme_classic()
      ggsave(paste0("./Output/did",
                    typelc,
                    "cand",
                    ifelse(cand=="Democrats", "dem", 
                           ifelse(cand=="Republicans", "rep", "all")), 
                    "_contrib",
                    ifelse(contrib=="Democrats", "dem", 
                           ifelse(contrib=="Republicans", "rep", "all")), 
                    ".pdf"),
             width=7, height=5)
      
      temp_data <- plotdata %>% 
        filter(type==t &   
                 contrib_party==contrib & 
                 district_covs %in% c("No FEs") & 
                 cand_party==cand & 
                 dvr!="") %>%
        mutate(contrib_gender = ifelse(str_detect(X, "1"), "Female", "Male"),
               label = ifelse(str_detect(X, "B"), "Black\nCandidate",
                              ifelse(str_detect(X, "H"), "Latino\nCandidate",
                                     ifelse(str_detect(X, "A"), "Asian\nCandidate", "White\nCandidate"))))
      
      
      if(nrow(temp_data)==0){next}
      
      ggplot(temp_data, 
             aes(x=label, y=b, color=contrib_gender)) +
        geom_point(position=pd) +
        geom_errorbar(aes(ymin=cilow, ymax=cihigh), width=0, position=pd) +
        facet_grid(dvg~dvr) +
        xlab("") +
        ylab(paste0(t, " of ", 
                    ifelse(contrib=="Democrats", "Dem. ", 
                           ifelse(contrib=="Republicans", "Rep. ", "")), 
                    "General Election Individual Contribs.")) +
        geom_hline(aes(yintercept=0), linetype=2, color="black") +
        scale_color_manual(values=c("black", "grey"), name="Candidate\nGender") +
        #scale_x_discrete(labels=labels) +
        coord_flip(ylim=ylims) +
        theme_classic()
      ggsave(paste0("./Output/did",
                    typelc,
                    "cand",
                    ifelse(cand=="Democrats", "dem", 
                           ifelse(cand=="Republicans", "rep", "all")), 
                    "_contrib",
                    ifelse(contrib=="Democrats", "dem", 
                           ifelse(contrib=="Republicans", "rep", "all")), 
                    "_nofe.pdf"),
             width=7, height=5)
    }
  }
}

# creating custom plot function to create plots on demand
custom.plot <- function(t, contrib, cand, fe, time, district_covs, axes){
  if(cand=="Democrats"){
    labels <- c("cand_H_d" = "Dem. Latino\nCandidate", 
                "cand_B_d" = "Dem. Black\nCandidate", 
                "cand_A_d" = "Dem. Asian\nCandidate")
  }
  if(cand=="Republicans"){
    labels <- c("cand_H_r" = "Rep. Latino\nCandidate", 
                "cand_B_r" = "Rep. Black\nCandidate", 
                "cand_A_r" = "Rep. Asian\nCandidate")
  }
  if(cand=="All"){
    labels <- c("cand_H_all" = "Latino\nCandidate", 
                "cand_B_all" = "Black\nCandidate", 
                "cand_A_all" = "Asian\nCandidate")
  }
  
  # getting info for filename
  typelc <- key[key$type==t, 'typelc']
  
  # setting axes
  ylims <- axes
  
  # fixed effects
  if(fe=="yes"){
    fe_set <- c("Yes", "No")
    legend_title <- "District\nControls"
    fe_save <- ""
  } else if(fe=="controls"){
    fe_set <- c("All", "No FEs")
    legend_title <- "Fixed\nEffects"
    fe_save <- "_controls"
  } else if(fe=="no"){
    fe_set <- c("Yes", "No")
    legend_title <- "District\nControls"
    fe_save <- "_nofe"
    }
  
  ggplot(plotdata[plotdata$type==t & 
                    plotdata$contrib_party==contrib & 
                    plotdata$district_covs %in% district_covs &
                    time %in% time &
                    fe==fe &
                    plotdata$cand_party==cand,], 
         aes(x=X, y=b, color=district_covs)) +
    geom_point(position=pd) +
    geom_errorbar(aes(ymin=cilow, ymax=cihigh), width=0, position=pd) +
    facet_wrap(~dv) +
    xlab("") +
    ylab(paste0(t, " of ", 
                ifelse(contrib=="Democrats", "Dem. ", 
                       ifelse(contrib=="Republicans", "Rep. ", "")), 
                "General Election Individual Contribs.")) +
    geom_hline(aes(yintercept=0), linetype=2, color="black") +
    scale_color_manual(values=c("grey","black"), labels = c("No", "Yes"), name=legend_title) +
    scale_x_discrete(labels=labels) +
    coord_flip(ylim=axes) +
    theme_classic()
  ggsave(paste0("./Output/custom_did",
                fe_save,
                typelc,
                "cand",
                ifelse(cand=="Democrats", "dem", 
                       ifelse(cand=="Republicans", "rep", "all")), 
                "_contrib",
                ifelse(contrib=="Democrats", "dem", 
                       ifelse(contrib=="Republicans", "rep", "all")), 
                ".pdf"),
         width=7, height=5)
}

# other stuff
contrib <- "Democrats"
labels <- c("cand_H_d" = "Dem. Latino\nCandidate", 
            "cand_B_d" = "Dem. Black\nCandidate", 
            "cand_A_d" = "Dem. Asian\nCandidate")
ggplot(plotdata[plotdata$type=="Log Total" & 
                  plotdata$contrib_party=="Democrats" & 
                  plotdata$district_covs!="All" & 
                  plotdata$dv=="Asian" & 
                  plotdata$cand_party=="Democrats" & plotdata$time=="General Election Money",], 
       aes(x=X, y=b, color=district_covs)) +
  geom_point(position=pd) +
  geom_errorbar(aes(ymin=cilow, ymax=cihigh), width=0, position=pd) +
  xlab("") +
  facet_wrap(~dv) +
  ylab(paste0("Log Total of ", 
              ifelse(contrib=="Democrats", "Dem. ", 
                     ifelse(contrib=="Republicans", "Rep. ", "")), 
              "General Election Individual Contribs.")) +
  geom_hline(aes(yintercept=0), linetype=2, color="black") +
  scale_color_manual(values=c("grey","black"), name="District\nControls") +
  scale_x_discrete(labels=labels) +
  coord_flip() +
  theme_classic()
ggsave("./Output/did_demcand_demcontrib_logtotal_A.pdf")

contrib <- "Republicans"
labels <- c("cand_H_d" = "Dem. Latino\nCandidate", 
            "cand_B_d" = "Dem. Black\nCandidate", 
            "cand_A_d" = "Dem. Asian\nCandidate")
ggplot(plotdata[plotdata$type=="Log Total" & 
                  plotdata$contrib_party=="Republicans" & 
                  plotdata$district_covs!="All" & 
                  plotdata$dv=="White" & 
                  plotdata$cand_party=="Democrats" & plotdata$time=="General Election Money",], 
       aes(x=X, y=b, color=district_covs)) +
  geom_point(position=pd) +
  geom_errorbar(aes(ymin=cilow, ymax=cihigh), width=0, position=pd) +
  facet_wrap(~dv) +
  xlab("") +
  ylab(paste0("Log Total of ", 
              ifelse(contrib=="Democrats", "Dem. ", 
                     ifelse(contrib=="Republicans", "Rep. ", "")), 
              "General Election Individual Contribs.")) +
  geom_hline(aes(yintercept=0), linetype=2, color="black") +
  scale_color_manual(values=c("grey","black"), name="District\nControls") +
  scale_x_discrete(labels=labels) +
  coord_flip() +
  theme_classic()
ggsave("./Output/did_demcand_repcontrib_logtotal_W.pdf")

pdf("./Output/did_demcandidate_demcontrib_share.pdf", w=7, h=5)
ggplot(plotdata[plotdata$type=="Share" & plotdata$contrib_party=="Democrats" 
                & plotdata$cand_party=="Democrats" & plotdata$time=="General Election Money",], 
       aes(x=X, y=b, color=district_covs)) +
  geom_point(position=pd) +
  geom_errorbar(aes(ymin=cilow, ymax=cihigh), width=0, position=pd) +
  facet_wrap(~dv) +
  xlab("") +
  ylab("Share of Dem. General Election Individual Contribs.") +
  geom_hline(aes(yintercept=0), linetype=2, color="black") +
  scale_color_manual(values=c("grey","black"), name="District\nControls") +
  scale_x_discrete(labels=c("cand_H_d" = "Dem. Latino\nCandidate", 
                            "cand_B_d" = "Dem. Black\nCandidate", 
                            "cand_A_d" = "Dem. Asian\nCandidate")) +
  coord_flip() +
  theme_classic()
dev.off()


pdf("did_demcandidate_demcontrib_logtotal.pdf", w=7, h=5)
ggplot(plotdata[plotdata$type=="Log Total" & plotdata$contrib_party=="Democrats" 
                & plotdata$cand_party=="Democrats" & plotdata$time=="General Election Money",], 
       aes(x=X, y=b, color=district_covs)) +
  geom_point(position=pd) +
  geom_errorbar(aes(ymin=cilow, ymax=cihigh), width=0, position=pd) +
  facet_wrap(~dv) +
  xlab("") +
  ylab("Log Total of Dem. General Election Individual Contribs.") +
  geom_hline(aes(yintercept=0), linetype=2, color="black") +
  scale_color_manual(values=c("grey","black"), name="District\nControls") +
  scale_x_discrete(labels=c("cand_H_d" = "Dem. Latino\nCandidate", 
                            "cand_B_d" = "Dem. Black\nCandidate", 
                            "cand_A_d" = "Dem. Asian\nCandidate")) +
  coord_flip() +
  theme_classic()
dev.off()


pdf("did_demcandidate_repcontrib_share.pdf", w=7, h=5)
ggplot(plotdata[plotdata$type=="Share" & plotdata$contrib_party=="Republicans" 
                & plotdata$cand_party=="Democrats" & plotdata$time=="General Election Money",], 
       aes(x=X, y=b, color=district_covs)) +
  geom_point(position=pd) +
  geom_errorbar(aes(ymin=cilow, ymax=cihigh), width=0, position=pd) +
  facet_wrap(~dv) +
  xlab("") +
  ylab("Log Total of Rep General Election Individual Contribs.") +
  geom_hline(aes(yintercept=0), linetype=2, color="black") +
  scale_color_manual(values=c("grey","black"), name="District\nControls") +
  scale_x_discrete(labels=c("cand_H_d" = "Dem. Latino\nCandidate", 
                            "cand_B_d" = "Dem. Black\nCandidate", 
                            "cand_A_d" = "Dem. Asian\nCandidate")) +
  coord_flip() +
  theme_classic()
dev.off()

pdf("did_demcandidate_repcontrib_logtotal.pdf", w=7, h=5)
ggplot(plotdata[plotdata$type=="Log Total" & plotdata$contrib_party=="Republicans" 
                & plotdata$cand_party=="Democrats" & plotdata$time=="General Election Money",], 
       aes(x=X, y=b, color=district_covs)) +
  geom_point(position=pd) +
  geom_errorbar(aes(ymin=cilow, ymax=cihigh), width=0, position=pd) +
  facet_wrap(~dv) +
  xlab("") +
  ylab("Log Total of Rep General Election Individual Contribs.") +
  geom_hline(aes(yintercept=0), linetype=2, color="black") +
  scale_color_manual(values=c("grey","black"), name="District\nControls") +
  scale_x_discrete(labels=c("cand_H_d" = "Dem. Latino\nCandidate", 
                            "cand_B_d" = "Dem. Black\nCandidate", 
                            "cand_A_d" = "Dem. Asian\nCandidate")) +
  coord_flip() +
  theme_classic()
dev.off()






########Fundraising parity#######

data <- read.csv("house_candnw_totaldiff.csv", stringsAsFactors = F)

data <- data[grepl("cand", data$X),]

data <- cbind(data[1:3, 1:3], data[4:6, 4:5])

data$X[grepl("A", data$X)] <- "Asian cand."
data$X[grepl("B", data$X)] <- "Black cand."
data$X[grepl("H", data$X)] <- "Latino cand."

data[2:5] <- apply(data[2:5], 2, as.numeric)

data[2:5] <- round(data[2:5], digits=3)

names(data) <- c("Variable", "Est.", "SE", "Est.", "SE")


stargazer(data, out="../../Output/house_candnw_totaldiff.tex", 
          summary=F, style="ajps", rownames=F, digits=3, digits.extra=3)



##############InGroup Shared Race Gender##############


ingroup.files <- list.files(path='./Output/',
                            pattern = "ingroup.*csv")

output <- list()

for(i in ingroup.files){
  
  temp <- read.csv(paste0('./Output/', i), na.strings = c("","."), skip=1)[,c(1,6:7)]
  
  if(grepl("_dem", i)==T){
    
    temp$party <- "Democrats"
  }
  
  if(grepl("_rep", i)==T){
    
    temp$party <- "Republicans"
  }
  
  if(grepl("_woc", i)==T){
    
    temp$identity <- "Women of\nColor"
  }
  
  if(grepl("_women", i)==T){
    
    temp$identity <- "All Women"
  }
  
  if(grepl("_nofe", i)==T){
    
    temp$fe <- "No Fixed Effects"
  }else{temp$fe <- "District Fixed Effects"}
  
  if(grepl("_total_", i)==T){
    temp$dv <- "Total"
  }
  else if(grepl("_logtotal_", i)==T){
    temp$dv <- "Log Total"
  }else{temp$dv <- "Log Total All"}
  
  if(grepl("_ideo_", i)==T){
    temp$covar <- "Ideological Covariates"
  }
  else if(grepl("_comp_", i)==T){
    temp$covar <- "Competitiveness Covariates"
  }else{temp$covar <- "No Covariates"}
  
  output[[i]] <- temp
  
}

plotdata <- do.call(plyr::rbind.fill, output)

plotdata$identity[is.na(plotdata$identity)] <- "All Donors"

plotdata$variable[grepl("_race", plotdata$X)==T & grepl("_gender", plotdata$X)==F] <- "Shared Race"
plotdata$variable[grepl("_race", plotdata$X)==F & grepl("_gender", plotdata$X)==T] <- "Shared Gender"
plotdata$variable[grepl("_race", plotdata$X)==T & grepl("_gender", plotdata$X)==T] <- "Interaction"

plotdata$cilow <- plotdata$b.2 - 1.96*as.numeric(as.character(plotdata$se.2))
plotdata$cihigh <- plotdata$b.2 + 1.96*as.numeric(as.character(plotdata$se.2))

plotdata$b.2[is.na(plotdata$cilow)] <- NA

pd <- position_dodge(.4)

## FIGURE 3 IN MANUSCRIPT ##
pdf("./Output/did_ingroup_dem_rep.pdf", w=7, h=4)
ggplot(plotdata %>% filter(!is.na(variable) & 
                             !is.na(party) & 
                             fe=="District Fixed Effects" & 
                             dv=="Log Total" &
                             covar=="No Covariates"), 
       aes(x=variable, y=b.2, color=identity, shape=identity)) +
  geom_point(position=pd, size=2.5) +
  geom_errorbar(aes(ymin=cilow, ymax=cihigh), width=0, position=pd, size=1) +
  facet_wrap(~party) +
  xlab("") +
  ylab("Log Total of General Election Individual Contribs.") +
  geom_hline(aes(yintercept=0), linetype=2, color="black") +
  scale_color_grey() +
  #scale_color_manual(values=c("black","grey40", "grey"), name="Donors") +
  coord_flip() +
  theme_classic()
dev.off()

pdf("./Output/did_ingroup_dem_rep_comb.jpeg", w=7, h=4)
ggplot(plotdata %>% filter(!is.na(variable) & 
                             !is.na(party) & 
                             fe=="District Fixed Effects" & 
                             dv=="Log Total All" &
                             covar=="No Covariates"), 
       aes(x=variable, y=b.2, color=identity, shape=identity)) +
  geom_point(position=pd, size=2.5) +
  geom_errorbar(aes(ymin=cilow, ymax=cihigh), width=0, position=pd, size=1) +
  facet_wrap(~party) +
  xlab("") +
  ylab("Log Total of All Election Individual Contribs.") +
  geom_hline(aes(yintercept=0), linetype=2, color="black") +
  scale_color_grey() +
  #scale_color_manual(values=c("black","grey40", "grey"), name="Donors") +
  coord_flip() +
  theme_classic()
dev.off()

pdf("./Output/did_ingroup_dem_rep_comp.pdf", w=7, h=4)
ggplot(plotdata %>% filter(!is.na(variable) & 
                             !is.na(party) & 
                             fe=="District Fixed Effects" & 
                             dv=="Log Total" &
                             covar=="Competitiveness Covariates"), 
       aes(x=variable, y=b.2, color=identity, shape=identity)) +
  geom_point(position=pd, size=2.5) +
  geom_errorbar(aes(ymin=cilow, ymax=cihigh), width=0, position=pd, size=1) +
  facet_wrap(~party) +
  xlab("") +
  ylab("Log Total of General Election Individual Contribs.") +
  geom_hline(aes(yintercept=0), linetype=2, color="black") +
  scale_color_grey() +
  #scale_color_manual(values=c("black","grey40", "grey"), name="Donors") +
  coord_flip() +
  theme_classic()
dev.off()

pdf("./Output/did_ingroup_dem_rep_ideo.pdf", w=7, h=4)
ggplot(plotdata %>% filter(!is.na(variable) & 
                             !is.na(party) & 
                             fe=="District Fixed Effects" & 
                             dv=="Log Total" &
                             covar=="Ideological Covariates"), 
       aes(x=variable, y=b.2, color=identity, shape=identity)) +
  geom_point(position=pd, size=2.5) +
  geom_errorbar(aes(ymin=cilow, ymax=cihigh), width=0, position=pd, size=1) +
  facet_wrap(~party) +
  xlab("") +
  ylab("Log Total of General Election Individual Contribs.") +
  geom_hline(aes(yintercept=0), linetype=2, color="black") +
  scale_color_grey() +
  #scale_color_manual(values=c("black","grey40", "grey"), name="Donors") +
  coord_flip() +
  theme_classic()
dev.off()

pdf("./Output/did_ingroup_dem_rep_total.pdf", w=7, h=4)
ggplot(plotdata %>% filter(!is.na(variable) & 
                             !is.na(party) & 
                             fe=="District Fixed Effects" & 
                             dv=="Total" &
                             covar=="No Covariates"), 
       aes(x=variable, y=b.2, color=identity, shape=identity)) +
  geom_point(position=pd, size=2.5) +
  geom_errorbar(aes(ymin=cilow, ymax=cihigh), width=0, position=pd, size=1) +
  facet_wrap(~party) +
  xlab("") +
  ylab("Total General Election Individual Contribs.") +
  geom_hline(aes(yintercept=0), linetype=2, color="black") +
  scale_color_grey() +
  #scale_color_manual(values=c("black","grey40", "grey"), name="Donors") +
  coord_flip() +
  theme_classic()
dev.off()

pdf("did_ingroup_dem_rep_nofe.pdf", w=7, h=4)
ggplot(plotdata %>% filter(!is.na(variable) & 
                             !is.na(party) & 
                             fe=="No Fixed Effects" & 
                             dv=="Log Total" &
                             covar=="No Covariates"), 
       aes(x=variable, y=b.2, color=identity, shape=identity)) +
  geom_point(position=pd, size=2.5) +
  geom_errorbar(aes(ymin=cilow, ymax=cihigh), width=0, position=pd, size=1) +
  facet_wrap(~party) +
  xlab("") +
  ylab("Log Total of General Election Individual Contribs.") +
  geom_hline(aes(yintercept=0), linetype=2, color="black") +
  scale_color_grey() +
  #scale_color_manual(values=c("black","grey40", "grey"), name="Donors") +
  coord_flip() +
  theme_classic()
dev.off()

## GRANGER CAUSALITY TEST ##
reg <- read.csv('./Output/granger_ingroup_gender_race_logtotal_dem_women.csv',
                stringsAsFactors = F, skip=1) %>%
  mutate(est = as.numeric(ifelse(is.na(b.1), b, b.1)),
         err = as.numeric(ifelse(se=="", se.1, se)),
         name = ifelse(str_detect(X, 'gender'), "Shared Gender", ifelse(str_detect(X, 'race'), "Shared Race", NA))) %>%
  filter(!is.na(name)) %>%
  mutate(x = rep(c('4','3','2','1'),2)) %>%
  arrange(x)

ggplot(reg, aes(x=x, y=est)) +
  geom_point() +
  geom_errorbar(aes(ymin=est-err*1.96, ymax=est+err*1.96), width=0, size=1) +
  facet_wrap(~name, ncol=1) +
  xlab("") +
  ylab("Effect on Log Total Contributions") +
  geom_hline(aes(yintercept=0), linetype=2, color="black") +
  scale_x_discrete(labels = c('t-6','t-4','t-2','t')) + 
  scale_color_grey() +
  #scale_color_manual(values=c("black","grey40", "grey"), name="Donors") +
  #coord_flip() +
  theme_classic()
ggsave('./Output/granger test.pdf', height=8, width=8)
